package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrdersService;
import com.sky.service.ShoppingCartService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderListVO;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class OrdersServiceImpl implements OrdersService {
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private WebSocketServer webSocketServer;
    /**
     * 提交订单
     * */
    @Transactional
    @Override
    public OrderSubmitVO submit(OrdersSubmitDTO dto) {
        // 查询地址簿获取收获人信息
        AddressBook addressBook = addressBookMapper.getById(dto.getAddressBookId());
        if (addressBook == null) {
            // 地址为空，不能下单
            throw new OrderBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        // 查询用户表获取用户信息
        User user = userMapper.getById(BaseContext.getCurrentId());
        if (user == null) {
            throw new OrderBusinessException(MessageConstant.USER_NOT_LOGIN);
        }
        // 查询购物车
        List<ShoppingCart> carts = shoppingCartMapper.getByUserId(user.getId());
        if (carts == null) {
            throw new OrderBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //1 构造订单数据，存入orders表
        Orders orders = new Orders();
        BeanUtils.copyProperties(dto, orders);
        orders.setNumber(System.currentTimeMillis()+""); // 订单编号
        orders.setStatus(Orders.PENDING_PAYMENT); // 订单状态 待付款
        orders.setUserId(BaseContext.getCurrentId()); // 用户id
        orders.setOrderTime(LocalDateTime.now()); // 下单时间
        orders.setPayStatus(Orders.UN_PAID);// Z支付状态
        orders.setPhone(addressBook.getPhone()); // 收获电话
        orders.setAddress(addressBook.getDetail()); // 地址
        orders.setConsignee(addressBook.getConsignee()); // 收货人
        orders.setUserName(user.getName()); //下单人
        ordersMapper.add(orders);
        log.info("订单id{}",orders.getId());
        //2 构造订单详细明细数据，存入order——detail
        List<OrderDetail> list = new ArrayList<>();
        for (ShoppingCart cart : carts) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail,"id");
            orderDetail.setOrderId(orders.getId());
            list.add(orderDetail);

        }
        orderDetailMapper.addBatch(list);
        //3 删除购物车
        shoppingCartMapper.cleanCart(user.getId());
        //4 封装返回数据
        return OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();
    }
    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
//        Long userId = BaseContext.getCurrentId();
//        User user = userMapper.getById(userId);
//
//        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
//
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }
//
//        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
//        vo.setPackageStr(jsonObject.getString("package"));
//
//        return vo;

        // 模拟支付成功
        // 修改订单状态
        paySuccess(ordersPaymentDTO.getOrderNumber());
        return new OrderPaymentVO();
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = ordersMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        ordersMapper.update(orders);
        // 通过webSocket想客户端群发消息
        Map map = new HashMap();
        map.put("type",1);
        map.put("orderId",orders.getId());
        map.put("content","订单号："+ outTradeNo);
        String jsonString = JSONObject.toJSONString(map);
        webSocketServer.sendToAllClient(jsonString);
    }
    /**
     * 查询订单
     * */
    @Override
    public PageResult getHistoryOrders(OrdersPageQueryDTO dto) {
        // 设置分页参数
        PageHelper.startPage(dto.getPage(),dto.getPageSize());
        // 如果是用户访问，设置用户id
        if (BaseContext.getRole().equals("user")){
            dto.setUserId(BaseContext.getCurrentId());
        }

        // 分页查询订单表
        List<OrderListVO> list = ordersMapper.getHistoryOrders(dto);
        // 补充订单详细信息
        list.forEach(order -> {
            List<OrderDetail> details = orderDetailMapper.getByOrderId(order.getId());
            // 补充详细订单
            order.setOrderDetailList(details);
            // 如果是管理员身份且不是根据id查询菜品，将菜品名字存入
            if(BaseContext.getRole().equals("admin") && dto.getId() == null){
                for (OrderDetail detail : details) {
                    if (order.getOrderDishes() == null){
                        order.setOrderDishes(detail.getName());
                    }else {
                        order.setOrderDishes(order.getOrderDishes() +","+ detail.getName());
                    }
                }
            }
        });
        Page page = (Page) list;
        return new PageResult(page.getTotal(),page.getResult());
    }
    /**
     * 取消订单
     * */
    @Override
    public void cancel(Long id) {
        // 查询订单状态
        Integer status = ordersMapper.getStatusById(id);
        if (status == Orders.PENDING_PAYMENT || status == Orders.TO_BE_CONFIRMED) {
            // 如果订单状态时待付款和待接单可直接取消
            Orders orders = new Orders();
            orders.setId(id);
            orders.setStatus(Orders.CANCELLED);
            orders.setCancelReason("用户手动取消");
            orders.setCancelTime(LocalDateTime.now());
            ordersMapper.update(orders);
        }else {
            throw new OrderBusinessException(MessageConstant.ORDER_CANCEL_ERROR);
        }
    }
    /**
     * 再来一单
     * */
    @Override
    public void repetition(Long id) {
        // 根据订单id查询订单详细表
        List<OrderDetail> list = orderDetailMapper.getByOrderId(id);
        list.forEach(orderDetail -> {
            ShoppingCartDTO dto = new ShoppingCartDTO();
            BeanUtils.copyProperties(orderDetail,dto);
            shoppingCartService.addCart(dto);
        });
    }
    /**
     * 统计各状态订单数量（管理端）
     * */
    @Override
    public OrderStatisticsVO statistics() {
        return ordersMapper.statistics();
    }
    /**
     * 接单
     * */
    @Override
    public void confirm(OrdersConfirmDTO dto) {
        // 查询订单状态
        Integer status = ordersMapper.getStatusById(dto.getId());
        // 如果是待接单状态进行修改状态
        if (status == Orders.TO_BE_CONFIRMED) {
            Orders orders = new Orders();
            orders.setId(dto.getId());
            orders.setStatus(Orders.CONFIRMED);
            ordersMapper.update(orders);
        }else {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
    }
    /**
     * 拒单
     * */
    @Override
    public void rejection(OrdersRejectionDTO dto) {
        // 查询订单状态
        Integer status = ordersMapper.getStatusById(dto.getId());
        // 如果是待接单状态进行修改状态
        if (status == Orders.TO_BE_CONFIRMED) {
            // TODO : 退款操作
            Orders orders = new Orders();
            orders.setId(dto.getId());
            orders.setStatus(Orders.CANCELLED);
            orders.setCancelTime(LocalDateTime.now());
            orders.setRejectionReason(dto.getRejectionReason());
            ordersMapper.update(orders);
        }else {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
    }
    /**
     * 商家取消订单
     * */
    @Override
    public void adminCancel(OrdersCancelDTO dto) {
        // 查询订单状态
        Integer status = ordersMapper.getStatusById(dto.getId());
        if (status == Orders.PENDING_PAYMENT || status == Orders.CONFIRMED || status == Orders.DELIVERY_IN_PROGRESS || status == Orders.COMPLETED) {
            // 如果订单状态时待付款和待接单可直接取消
            Orders orders = new Orders();
            orders.setId(dto.getId());
            orders.setStatus(Orders.CANCELLED);
            orders.setCancelTime(LocalDateTime.now());
            orders.setCancelReason(dto.getCancelReason());
            ordersMapper.update(orders);
        }else {
            throw new OrderBusinessException(MessageConstant.ORDER_CANCEL_ERROR);
        }
    }
    /**
     * 派送订单
     * */
    @Override
    public void delivery(Long id) {
        // 查询订单状态
        Integer status = ordersMapper.getStatusById(id);
        if (status == Orders.CONFIRMED) {
            // 如果订单状态时待付款和待接单可直接取消
            Orders orders = new Orders();
            orders.setId(id);
            orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
            ordersMapper.update(orders);
        }else {
            throw new OrderBusinessException(MessageConstant.ORDER_CANCEL_ERROR);
        }
    }
    /**
     * 完成订单
     * */
    @Override
    public void complete(Long id) {
        // 查询订单状态
        Integer status = ordersMapper.getStatusById(id);
        if (status == Orders.DELIVERY_IN_PROGRESS) {
            // 如果订单状态时待付款和待接单可直接取消
            Orders orders = new Orders();
            orders.setId(id);
            orders.setStatus(Orders.COMPLETED);
            orders.setDeliveryTime(LocalDateTime.now());
            ordersMapper.update(orders);
        }else {
            throw new OrderBusinessException(MessageConstant.ORDER_CANCEL_ERROR);
        }
    }
    /**
     * 用户催单
     * */
    @Override
    public void reminder(Long id) {
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setId(id);

        // 根据id查询订单
        List<OrderListVO> historyOrders = ordersMapper.getHistoryOrders(ordersPageQueryDTO);
        if (historyOrders==null || historyOrders.isEmpty()) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Map map = new HashMap();
        map.put("type",2);
        map.put("orderId",id);
        map.put("content","订单号："+historyOrders.get(0).getNumber());

        webSocketServer.sendToAllClient(JSONObject.toJSONString(map));
        log.info("催单成功：{}",map);
    }


}
